package kr.co.iniline.rumkb.server;

import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

public class User {
	String userID = null;
	boolean isCreator = false;
	Queue<RmkbEvent> queue = null;
	boolean isInitRegistKub = false;
	
	int ownKubs[] = new int[0];
	
	public User(String id, boolean isCreator) {
		this.userID = id;
		this.isCreator = isCreator;
		init();
	}
	
	public User(String id) {
		this.userID = id;
		init();
	}
	
	void init() {
		queue = new ArrayBlockingQueue<RmkbEvent>(20);
	}
	
	public void informEvent(RmkbEvent event) {
		try {
			queue.add( event );
		} catch (IllegalStateException e) {
			System.out.println(userID+" is not activated.");
			queue.clear();
			//none-active user
		}
		if( event instanceof RmkbEvent.KubDeploy ) {
			addKubs( ((RmkbEvent.KubDeploy) event).getKubs() );
		}
	}
	
	public int getKubNum() {
		return ownKubs.length;
	}
	
	public int getKub(int index) {
		return ownKubs[index];
	}
	
	public int getKubTotalPoint() {
		return 0;
	}
	
	public void addKub(int kub) {
		addKubs( new int[]{kub} );
	}
	
	public void addKubs(int kubs[]) {
		int newKubs[] = new int[ownKubs.length + kubs.length];
		System.arraycopy(ownKubs, 0, newKubs, 0, ownKubs.length);
		System.arraycopy(kubs, 0, newKubs, ownKubs.length, kubs.length);
		ownKubs = newKubs;
	}
	
	public boolean hasKub(int kub) {
		return hasKubs(new int[]{kub});
	}
	
	public boolean hasKubs(int kubs[]) {
		for (int i = 0; i < kubs.length; i++) {
			boolean flag = false;
			for (int j = 0; j < ownKubs.length; j++) {
				if( kubs[i] != ownKubs[j] ) {
					flag = true;
				}
			}
			if( !flag ) return false;
		}
		return true;
	}
	
	public void removeKub(int kub) {
		removeKubs(new int[]{kub});
	}
	
	public void removeKubs(int kubs[]) {
		int newKubs[] = new int[ownKubs.length - kubs.length];
		int count = 0;
		for (int i = 0; i < kubs.length; i++) {
			for (int j = 0; j < ownKubs.length; j++) {
				if( kubs[i] == kubs[j] ) {
					break;
				} else {
					newKubs[count++] = kubs[j];
				}
			}
		}
	}
	
	public boolean isInitRegist() {
		return isInitRegistKub;
	}
	
	public void setInitRegist(boolean flag) {
		isInitRegistKub = flag;
	}
	
	public void reset() {
		ownKubs = new int[0];
		setInitRegist(false);
	}
	
	public RmkbEvent getEvent() {
		if( queue.size() == 0 ) {
			return null;
		} else {
			return queue.poll();
		}
	}
}
